package com.ysm.smfu.chat;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;

import com.ysm.smfu.R;
import com.ysm.smfu.protocal.BaseProtocal;
import com.ysm.smfu.utils.PrintUtil;
import com.ysm.smfu.utils.UIUtils;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import chatuidemo.ui.ChatActivity;
import easeui.EaseConstant;
import easeui.widget.EaseConversationList;

/**
 * Created by Administrator on 2016/10/20.
 * <p/>
 * //删除和某个user会话，如果需要保留聊天记录，传false
 * EMClient.getInstance().chatManager().deleteConversation(username, true);
 */
public class ZHConversationListFragment extends Fragment {
    @BindView(R.id.list)
    EaseConversationList conversationListView;
    @BindView(R.id.nomsg)
    ImageView nomsg;

    protected List<EMConversation> conversationList = new ArrayList<EMConversation>();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = UIUtils.inflate(R.layout.fragment_conversationlist);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getConversation();
    }

    /**
     * 获取会话信息
     */
    private void getConversation() {
        if (conversationList == null || conversationListView == null || nomsg == null)
            return;

        conversationList.clear();
        List<EMConversation> emConversations = loadConversationList();
        conversationList.addAll(emConversations);
        if (conversationList.size() == 0) {
            conversationListView.setVisibility(View.GONE);
            nomsg.setVisibility(View.VISIBLE);
            return;
        }
        conversationListView.setVisibility(View.VISIBLE);
        nomsg.setVisibility(View.GONE);
        conversationListView.init(conversationList);
        conversationListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                EMConversation conversation = conversationListView.getItem(position);
                UIUtils.startActivity(new Intent(getActivity(), ChatActivity.class).putExtra(EaseConstant.EXTRA_USER_ID, conversation.getUserName()));
            }
        });
    }

    protected List<EMConversation> loadConversationList() {
        // 获取所有聊天信息
        Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
        List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
                }
            }
        }
        try {
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {

        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        for (Pair<Long, EMConversation> sortItem : sortList) {
            list.add(sortItem.second);
        }
        PrintUtil.printRespones("加载聊天信息：" + list + "---" + list.size() + "---");
        return list;
    }

    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {

                if (con1.first.equals(con2.first)) {
                    return 0;
                } else if (con2.first.longValue() > con1.first.longValue()) {
                    return 1;
                } else {
                    return -1;
                }
            }

        });
    }

    public void fresh() {
        if (BaseProtocal.isGoLogin(true))
            return;
        getConversation();
    }

    /**
     * 清空消息列表
     */
    public void clearConversation() {
        if (conversationListView == null || conversationList == null || nomsg == null)
            return;
        conversationList.clear();
        conversationListView.init(conversationList);
        nomsg.setVisibility(View.VISIBLE);
    }
}
